/**
 * 
 */
package com.dfhc.pub.service;

import java.io.IOException;
import java.io.InputStream;

import org.quickbundle.project.RmProjectHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.dfhc.ISystemConstant;
import com.dfhc.PjException;
import com.dfhc.util.StringHelper;

/**
 * @author 龙色波
 * sql处理服务
 */
@Service
public class SqlProcessService {
	/**
	 * 执行sql
	 * @param multipartFile
	 */
	public void doExecsql(MultipartFile multipartFile) {
		if(multipartFile.isEmpty()){
			throw new PjException("缺少文件");
		}
		String sql="";
		try {
			InputStream in = multipartFile.getInputStream();
			byte b[];
			b = new byte[in.available()];
			in.read(b);
			String sqls = new String(b,ISystemConstant.ENCODE_UTF_8);
			//拆分sql为多行，逗号分隔
			String[] sqlArray = StringHelper.splitString(sqls, ";");
			for(int i=0;i<sqlArray.length;i++){
				sql = sqlArray[i];
				do{
				  try{
					  if(!StringHelper.isEmpty(sql)){					
						RmProjectHelper.getCommonServiceInstance().doUpdate(sql);
						//如果执行成功，跳出循环
						break;
					  }else{
						  break;
					  }
				  } catch (Exception e) {
					  e.printStackTrace();
					  //如果出错，是可能;出现在字段值里头，要重新组装sql,尝试提取下一个sql合并为一个
					  i++;
					  if(i<sqlArray.length){
						  sql = sql+";"+sqlArray[i];
					  }else{
						  throw new PjException("执行到sql:"+sql+"出错!错误消息:"+e.getMessage());
					  }
				  }
				}while(i<sqlArray.length);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new PjException("执行到sql:"+sql+"出错!错误消息:"+e.getMessage());
		}
	}

}
